'use strict';

const { Service } = require('egg');
const { Op } = require('sequelize');

class CourseStartService extends Service {
  /**
   * 根据分页和搜索条件获取已开课的课程
   * @param {Object} where 查询用户的条件
   * @param {Number} page 当前分页
   * @param {Number} pageSize 当前页每页多少条

   */
  async getPage(where, page, pageSize) {
    const { CourseStart, Teacher,Course,CourseStudent } = this.ctx.model;
    try {
        const res = await CourseStart.findAndCountAll({
            where: {
                ...where
            },
            order:[
                // id 降序
                ['created_at','DESC']
            ],
            include: [
                {model: Teacher, as: 'teacher'},
                {model: Course, as: 'course'},
                {model: CourseStudent},
            ],
            offset: pageSize * (page - 1),
            limit: pageSize,
        });
        console.log(res)
        return res
    } catch (e) {
        console.log('00000', e)
    }
  }

  /**
   * 注册用户数据
   * @param {Object} data
   */
  async createItem(data) {
    const { CourseStart } = this.ctx.model;
    const userExists = await CourseStart.findOne({
      attributes: ['id'],
      where: {
          category_id: data.category_id,
          course_id: data.course_id,
          teacher_id: data.teacher_id,
      },
    });
    if (userExists) throw new Error('该老师已开此课程');
    const newUser = await CourseStart.create(data);
    return newUser.dataValues;
  }

  /**
   * 根据id删除对应的用户
   * @param {Number} uid
   */
  async deleteItemById(id) {
    return await this.ctx.model.CourseStart.destroy({ where: { id } });
  }

  /**
   * 根据ID修改用户信息
   * @param {Number} id 用户ID
   * @param {Object} data 要修改的用户信息
   */
  async updateItemById(id, data) {
    const { CourseStart } = this.ctx.model;
    const andWhere = { id: { [Op.ne]: id } };
      andWhere.category_id = data.category_id;
      andWhere.course_id = data.course_id;
      andWhere.teacher_id = data.teacher_id;
      const userExists = await CourseStart.findOne({
          attributes: ['id'],
          where: { [Op.and]: andWhere },
      });
      if (userExists) throw new Error('该老师已开此课程');
    return await CourseStart.update(data, { where: { id } });
  }
  // 所有列表
  async allList(where) {
      const { CourseStart, Teacher,Course,CourseStudent } = this.ctx.model;
      try {
          const res = await CourseStart.findAll({
              where: {
                  ...where
              },
              include: [
                  {model: Teacher, as: 'teacher'},
                  {model: Course, as: 'course'},
                  {model: CourseStudent},
              ],
          });
          console.log(res)
          return res
      } catch (e) {
          console.log('00000', e)
      }
  }
}

module.exports = CourseStartService;
